<template>
  <div class="user-profile-page">
    <!-- 顶部栏 -->
    <div class="top-bar">
      <button class="back-btn" @click="goBack">← 返回</button>
      <el-dropdown
        v-if="!isCurrentUser"
        trigger="click"
        @command="handleUserMenu"
      >
        <span class="more-btn">···</span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="report">举报</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 主页面内容 -->
    <div v-if="!isSubPage">
      <!-- 用户资料卡片 -->
      <div class="user-info-card">
        <img class="avatar" :src="user.avatar" alt="头像" />
        <div class="info">
          <div class="top-line">
            <div class="name">{{ user.name }}</div>
            <button v-if="isCurrentUser" class="edit-btn" @click="editProfile">
              编辑资料
            </button>
          </div>
          <div class="signature">
            {{ user.signature || 'TA 还没有设置个性签名' }}
          </div>
        </div>
      </div>

      <!-- 用户数据 -->
      <div class="stats">
        <div
          class="stat-item"
          v-for="s in stats"
          :key="s.label"
          @click="handleStatClick(s.label)"
        >
          <div class="value">{{ s.value }}</div>
          <div class="label">{{ s.label }}</div>
        </div>
      </div>

      <!-- Tab 导航 -->
      <div class="tab-nav">
        <div
          v-for="(tab, index) in tabs"
          :key="tab"
          :class="['tab-item', { active: currentTab === index }]"
          @click="currentTab = index"
        >
          {{ tab }}
        </div>
      </div>

      <div class="tab-content">
        <div v-if="currentTab === 0" class="dynamic-wrapper">
          <UserDynamicList :list="userDynamics" />
        </div>
        <div v-else class="tab-scroll">
          <UserArticleList :list="userArticles" />
        </div>
      </div>

      <!-- 非本人时显示底部操作栏 -->
      <!-- <div v-if="!isCurrentUser" class="user-profile-section-footer">
        <button
          class="user-profile-footer-btn msg-btn"
          @click="sendPrivateMessage"
        >
          <i class="hb-icon heybox-bbs_comment_filled_24x24"></i> 私信
        </button>
        <button
          class="user-profile-footer-btn follow-btn"
          :class="{ followed: isFollowed }"
          @click="toggleFollow"
        >
          <i class="hb-icon heybox-special_check_small_line_24x24"></i>
          {{ isFollowed ? '已关注' : '关注' }}
        </button>
      </div> -->
    </div>

    <!-- 子页面路由展示区 -->
    <router-view v-else />

    <!-- 自定义弹窗 -->
    <teleport to="body">
      <div v-if="showDialog" class="custom-dialog-mask">
        <div class="custom-dialog">
          <p class="dialog-text">
            你确定要{{ dialogActionText }} {{ user.name }} 吗？
          </p>
          <div class="dialog-buttons">
            <button @click="handleDialogConfirm" class="confirm-btn">
              确认
            </button>
            <button @click="handleDialogCancel" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </teleport>
  </div>
  <ReportDialog v-model="showReportDialog" @submit="handleReportSubmit" />
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getUserInfo, followUser } from '@/apis/user'
import { getUserDynamic } from '@/apis/dynamic'
import { getUserArticle } from '@/apis/article'
import { ElMessage } from 'element-plus'

import UserDynamicList from '@/views/User/components/UserDynamicList.vue'
import UserArticleList from '@/views/User/components/UserArticleList.vue'

import ReportDialog from '@/components/ReportDialog.vue'
import { reportTarget as reportApi } from '@/apis/report' // 引入接口方法
import { useMessageStore } from '@/stores/messageStore'

const router = useRouter()
const route = useRoute()

const myUid = localStorage.getItem('uid') || ''
const routeUid = computed(() => route.params.userId || myUid)

// 判断是否为本人页面
const isCurrentUser = computed(() => routeUid.value === myUid)

// ✅ 判断当前是否是“子页面”，如 edit、follow
const isSubPage = computed(() =>
  ['/edit', '/follow', '/fav', '/history'].some((sub) =>
    route.path.endsWith(sub)
  )
)
const user = ref({ name: '', avatar: '', level: 0, signature: '' })
const isFollowed = ref(false)
const stats = ref([
  { label: '关注', value: 0 },
  { label: '粉丝', value: 0 },
  { label: '收藏', value: 0 },
  { label: '历史记录', value: 0 },
])

const userDynamics = ref([])
const userArticles = ref([])

onMounted(() => {
  fetchUserInfo()
  fetchUserDynamics()
  fetchUserArticles()
  messageStore.loadSessions(myUid)
})

watch(
  () => route.params.userId,
  (newVal) => {
    if (newVal) {
      fetchUserInfo()
      fetchUserDynamics()
      fetchUserArticles()
    }
  }
)

const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo(routeUid.value)
    if (res.code === '200') {
      const data = res.data
      user.value = {
        name: data.username,
        avatar:
          data.avatar ||
          'https://read-images.oss-cn-beijing.aliyuncs.com/default.png',
        level: data.level || 1,
        signature: data.signature || '',
      }
      isFollowed.value = data.isFollowed
      stats.value = [
        { label: '关注', value: data.followCount || 0 },
        { label: '粉丝', value: data.fanCount || 0 },
        { label: '收藏', value: data.favCount || 0 },
        { label: '历史记录', value: data.historyCount || 0 },
      ]
    } else {
      ElMessage.error(res.message || '获取用户信息失败')
    }
  } catch {
    ElMessage.error('网络错误')
  }
}

const fetchUserDynamics = async () => {
  try {
    const res = await getUserDynamic(routeUid.value)
    if (res.code === '200') userDynamics.value = res.data
    else ElMessage.error(res.message || '获取动态失败')
  } catch {
    ElMessage.error('获取动态失败')
  }
}

const fetchUserArticles = async () => {
  try {
    const res = await getUserArticle(routeUid.value)
    if (res.code === '200') userArticles.value = res.data
  } catch {
    ElMessage.error('获取文章失败')
  }
}

const currentTab = ref(0)
const tabs = ['动态', '文章']

const editProfile = () => {
  router.push(`/home/user/${myUid}/edit`)
}

const handleStatClick = (label) => {
  if (label === '关注') {
    router.push(`/home/user/${routeUid.value}/follow?type=follow`)
  } else if (label === '粉丝') {
    router.push(`/home/user/${routeUid.value}/follow?type=fan`)
  } else if (label === '收藏') {
    // 新增收藏跳转
    router.push(`/home/user/${routeUid.value}/fav`)
  } else {
    router.push(`/home/user/${routeUid.value}/history`)
  }
}

const messageStore = useMessageStore() // 新增

const sendPrivateMessage = async () => {
  const targetUserId = route.params.userId

  try {
    // ✅ 先确保数据已加载
    await messageStore.loadSessions(myUid)

    const existingSession = messageStore.findSessionByUserId(targetUserId)
    console.log('相关session', existingSession)

    if (existingSession) {
      router.push(`/home/message?sessionId=${existingSession.sessionId}`)
    } else {
      // ✅ 正确处理响应数据
      const res = await messageStore.createSession(targetUserId)
      if (res?.data) {
        router.push(`/home/message?sessionId=${res.data.sessionId}`)
      }
    }
  } catch (err) {
    ElMessage.error('操作失败: ' + err.message)
  }
}

const showDialog = ref(false)
const dialogActionText = ref('关注')
let nextFollowStatus = false

const toggleFollow = () => {
  nextFollowStatus = !isFollowed.value
  dialogActionText.value = nextFollowStatus ? '关注' : '取消关注'
  showDialog.value = true
}

const handleDialogConfirm = async () => {
  showDialog.value = false
  try {
    const res = await followUser(routeUid.value, nextFollowStatus)
    if (res.code === '200') {
      isFollowed.value = nextFollowStatus
      ElMessage.success(`${dialogActionText.value}成功`)
    } else if (res.code === 'A0220') {
      ElMessage.warning('不能关注自己哦')
    } else {
      ElMessage.error(`${dialogActionText.value}失败，请稍后再试`)
    }
  } catch {
    ElMessage.error('关注操作失败')
  }
}

const handleDialogCancel = () => {
  showDialog.value = false
}

const goBack = () => router.back()

const showReportDialog = ref(false)
const reportTarget = ref(null)

const handleUserMenu = (command) => {
  if (command === 'report') {
    reportTarget.value = {
      targetId: routeUid.value,
      targetType: 4, // 用户为 targetType 4
    }
    showReportDialog.value = true
  }
}

const handleReportSubmit = async (payload) => {
  const finalData = {
    ...reportTarget.value,
    ...payload,
  }
  try {
    await reportApi(finalData)
    ElMessage.success('举报成功，平台将尽快处理')
  } catch (err) {
    ElMessage.error('举报失败，请稍后再试')
  }
}
</script>

<style scoped>
.user-profile-page {
  padding: 16px;
  background-color: #f9f9f9;
}
.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.back-btn {
  background: none;
  border: none;
  font-size: 16px;
  color: #007bff;
  cursor: pointer;
}
.user-info-card {
  display: flex;
  background: #fff;
  padding: 16px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
  margin-bottom: 12px;
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 16px;
}
.info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.top-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.name {
  font-size: 18px;
  font-weight: bold;
}
.edit-btn {
  padding: 4px 10px;
  font-size: 13px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}
.edit-btn:hover {
  background-color: #0056b3;
}
.signature {
  color: #666;
  font-size: 14px;
}
.stats {
  display: flex;
  justify-content: space-around;
  margin: 12px 0;
}
.stat-item {
  text-align: center;
}
.stat-item .value {
  font-weight: bold;
  font-size: 16px;
}
.stat-item .label {
  color: #888;
  font-size: 13px;
}
.tab-nav {
  display: flex;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  cursor: pointer;
  font-size: 15px;
  color: #666;
}
.tab-item.active {
  color: #007bff;
  font-weight: bold;
  border-bottom: 2px solid #007bff;
}

.dynamic-wrapper {
  max-width: 800px;
  padding: 0 20px;
  box-sizing: border-box;
  margin: 0 auto;
}
.tab-content {
  background: #fff;
  border-radius: 8px;
  height: 600px; /* ✅ 设置一个固定高度，根据页面情况调整 */
  overflow-y: auto; /* ✅ 添加垂直滚动条 */
  box-sizing: border-box;
}

.user-profile-section-footer {
  position: fixed;
  bottom: 0;
  width: 50%;
  background-color: #fff;
  padding: 12px 16px;
  display: flex;
  justify-content: space-around;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.04);
  z-index: 1000;
}

.user-profile-footer-btn {
  flex: 1;
  margin: 0 8px;
  padding: 10px 0;
  font-size: 14px;
  border-radius: 6px;
  border: 1px solid #007bff;
  background-color: #fff;
  color: #007bff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 私信按钮（灰色） */
.user-profile-footer-btn.msg-btn {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
}
/* 关注按钮默认样式（黑底白字） */
.user-profile-footer-btn.follow-btn {
  background-color: #000;
  color: #fff;
  border: 1px solid #000;
}

/* 已关注状态：灰底黑字 */
.user-profile-footer-btn.follow-btn.followed {
  background-color: #e0e0e0;
  color: #333;
  border: 1px solid #ccc;
}
.user-profile-footer-btn.secondary {
  background-color: #f0f8ff;
}

.user-profile-footer-btn i {
  margin-right: 6px;
  font-size: 16px;
}
.custom-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.custom-dialog {
  background-color: #fff;
  color: #000;
  padding: 20px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-width: 280px;
  text-align: center;
}

.dialog-text {
  font-size: 16px;
  margin-bottom: 20px;
}

.dialog-buttons {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.confirm-btn,
.cancel-btn {
  flex: 1;
  padding: 10px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  border: none;
}

.confirm-btn {
  background-color: #000;
  color: #fff;
}
.cancel-btn {
  background-color: #fff;
  color: #000;
  border: 1px solid #ccc;
}
.more-btn {
  margin-left: auto;
  font-size: 20px;
  cursor: pointer;
  color: #999;
  padding: 4px 8px;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  position: relative;
}

.spacer {
  flex: 1;
}
</style>
